package net.lwf.hibernate.dao.worksheet;

import java.util.Date;
import java.util.List;


import net.lwf.date.util.DateUtil;
import net.lwf.hibernate.dao.BaseDAO;
import net.lwf.hibernate.entity.worksheet.UserWsAccess;
import net.lwf.hibernate.util.HibernateUtil;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

public class WorkSheetAccessDAO extends BaseDAO {
	
	/**
	 * @param userid
	 * @param worksheetId
	 * @return
	 */
	public boolean workSheetAccessed(long userid, long worksheetId) {
		List<UserWsAccess> data = this.getUserWsAccessInfo(userid, worksheetId, null);
		if(data == null || data.size() == 0) {
			return false;
		}
		return true;
	}
	
	public boolean workSheetAccessed(long userid, String wsaccesskey) {
		List<UserWsAccess> data = getUserWsAccessInfo(userid, 0, wsaccesskey);
		if(data == null || data.size() == 0) {
			return false;
		}
		return true;
	}
	
	@SuppressWarnings("unchecked")
	private List<UserWsAccess> getUserWsAccessInfo(long userid, long worksheetId, String wsaccesskey) {
		List<UserWsAccess> data = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			Criteria criteria = session.createCriteria(UserWsAccess.class);
			if(userid != 0) {
				criteria.add(Restrictions.eq("userKey", new Long(userid)));
			}
			if(worksheetId != 0) {
				criteria.add(Restrictions.eq("wsAccessKey", wsaccesskey));
			}
			if(wsaccesskey != null && wsaccesskey.trim().length() != 0) {
				criteria.add(Restrictions.eq("wsAccessKey", wsaccesskey));
			}
			
			Date startDate = DateUtil.resetTime(0, 0, 0);
			Date endDate = DateUtil.resetTime(23, 59, 59);
			criteria.add(Restrictions.between("dateAccessed", new Date(startDate
					.getTime()), new Date(endDate.getTime())));

			data = criteria.list();

		} finally {
			if (session != null) {
				session.close();
			}
		}
		return data;
	}
	
	
	public void create(long userKey, long workSheetKey, String wsAccessKey) {
		UserWsAccess uwsaccess = new UserWsAccess();
		uwsaccess.setDateAccessed(new Date());
		uwsaccess.setUserKey(userKey);
		uwsaccess.setWorkSheetKey(workSheetKey);
		uwsaccess.setWsAccessKey(wsAccessKey);
		
		Transaction tx = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			tx = session.beginTransaction();
			session.save(uwsaccess);
			tx.commit();
		}
	    finally {
	    	if(session != null) {
	    		session.close();
	    	}
	    }
	}

}



